package it.sd.wdc.spider.executer;

import java.util.LinkedList;
import java.util.StringTokenizer;

import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class DocumentWrapper {

	Document doc = null;
	
	public DocumentWrapper(String rootname) throws Exception {
		this.doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();

		Element root = doc.createElement(rootname);
		doc.appendChild(root);
	}
	
	public Element getRootElement() {
		return this.doc.getDocumentElement();
	}
	
	public Element AddNodo(String nome) {
		Element element = doc.getDocumentElement();
		
		LinkedList<String> path = parseNome(nome);
		while (path.size()>0) {
			String nodo = path.removeFirst();
			boolean last = (path.size()==0);
			element = getOrCreate(element, nodo, last);
		}
		
		return element;
	}
	
	private Element getOrCreate(Element padre, String nodo, boolean last) {
		Element element = null;
	
		
		if (padre==null) { 
			element = doc.createElement(nodo);
			doc.appendChild(element);
		} else {
			if (!last) {
				element = getElementByName(padre, nodo);
			}
			if (element==null) {
				element = doc.createElement(nodo);
				padre.appendChild(element);
			}
		}
		
		return element;
	}
	
	private Element getElementByName(Element padre, String nome) {
		
		Element figlio = null;
		
		NodeList lista = padre.getChildNodes();
		for (int i = 0; i < lista.getLength(); i++) {
			Node node = lista.item(i);
			if (node instanceof Element) {
				Element x = (Element)node;
				if (nome.equals(x.getNodeName())) {
					figlio = x;
					break;
				}
			}
		}
		
		return figlio;
	}
	
	public LinkedList<Element> getChildElement(Element padre) {
		LinkedList<Element> lista  = new LinkedList<Element>();

		NodeList nodes = padre.getChildNodes();
		for (int i = 0; i < nodes.getLength(); i++) {
			Node node = nodes.item(i);
			if (node instanceof Element) {
				Element x = (Element)node;
				lista.add(x);
			}
		}
		
		return lista;
		
	}
	
	private LinkedList<String> parseNome(String nome) {
		LinkedList<String> path = new LinkedList<String>();
		
		StringTokenizer st = new StringTokenizer(nome, ".");
		while (st.hasMoreTokens()) {
			path.add(st.nextToken());
		}
		
		return path;
	}

}
